var fs = require('fs');
var Station = require('../models/station');
var Config = require('../models/config');

var configJson = fs.readFileSync('test.json').toString();
var configInfo = {};
var KEY = "base.conf";

function getConfigInfo(req, res) {
  configInfo.UWB = JSON.parse(configJson).UWB;
  configInfo.RTK = JSON.parse(configJson).RTK;
  configInfo.UWB[KEY] = [];
  configInfo.RTK[KEY] = [];
  Config.all().then(function (result) {
    configInfo.wrapper = result[0];
    getStations(result[0], res);
  })
}

function getStations(data, res) {
  Station.all().then(function (stations) {
    for (var i = 0; i < stations.length; i++) {
      if (data.rtk_bases.indexOf(stations[i].nodeID) > -1) {
        configInfo.RTK[KEY].push(stations[i])
      }
      if (data.uwb_bases.indexOf(stations[i].nodeID) > -1) {
        configInfo.UWB[KEY].push(stations[i]);
      }
    }
    res.send(configInfo)
  });
}

module.exports = {
  getConfigInfo: getConfigInfo,
  addStation: function (req, res) {
    // var newStation = {name: req.body.name, nodeID: req.body.nodeID, type: req.body.type, nodeNum: req.body.nodeNum};
    console.log(req.body)
    Station.create(req.body).then(function (result) {
      res.send(result)
    }, function (error) {
      res.send({status: false, message: error})
    })
  },
  getAllStationInfo: function (req, res) {
    Station.all().then(function (stations) {
      res.send(stations)
    }, function (error) {
      res.send({status: 400, message: error})
    })
  },
  getStationInfo: function (req, res) {
    Station.findByType(req.query.nodeType).then(
      function (stations) {
        res.send(stations)
      }, function (error) {
        res.send({status: 400, message: error})
      })
  },
  deleteStation: function (req, res) {
    Station.delete(req.body.nodeID).then(function (result) {
      res.send({status: true})
    }, function (error) {
      res.send({status: 400, message: error})
    })
  },
  updateStation: function (req, res) {
    var data = {
      name: req.body.name,
      nodeID: req.body.id,
      nodeType:req.body.nodeType,
      x: req.body.x,
      y: req.body.y,
      z: req.body.z
    };
    console.log('===========stations 更新信息')
    console.log(req.body);
    Station.update({nodeID: Number(req.body.nodeID)}, data, req.body.history).then(function (result) {
      res.send(result)
    }, function (error) {
      res.send({status: false, message: error})
    })
  }
};